package org.sourcecode.common.freemarker;

import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sourcecode.common.statichtml.GetStatichtml;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateNumberModel;
import freemarker.template.TemplateScalarModel;

public class StatichtmlDirective implements TemplateDirectiveModel{

	protected final  Log log = LogFactory.getLog(getClass());
	
	protected GetStatichtml getStatichtml;
	
	public static final String PARAME_URL = "url";
	
	public static final String PARAME_FLUSH = "flush";
	
	private static final long time = 180 * 1000 * 10;
	
	@SuppressWarnings("rawtypes")
	public void execute(Environment env, Map params, TemplateModel[] loopVars,
			TemplateDirectiveBody body) throws TemplateException, IOException {
		Iterator iter = params.entrySet().iterator();
		String url = "";
		long flush = time;
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			String paramName = (String) entry.getKey();
			TemplateModel paramValue = (TemplateModel) entry.getValue();
			if (paramValue != null) {
				if (paramName.equals(PARAME_URL)) {
					url = ((TemplateScalarModel)paramValue).getAsString().trim();
				} else if (paramName.equals(PARAME_FLUSH)) {
					flush = ((TemplateNumberModel)paramValue).getAsNumber().longValue();
				}
			}
		}
		
		String content = getStatichtml.gethtml(url, flush);
	
		if (content == null) content = "";
		Writer out = env.getOut();
		out.write(content);
		out.flush();
	}

	public void setGetStatichtml(GetStatichtml getStatichtml) {
		this.getStatichtml = getStatichtml;
	}
	
	
}
